home *** CD-ROM | disk | FTP | other *** search
- Path: damage.usa1.net!news
- From: Kin Chan <firstian@usa1.com>
- Newsgroups: comp.lang.c++
- Subject: Re: const member functions
- Date: Mon, 15 Jan 1996 14:09:53 +0000
- Organization: USAinternet, Inc.
- Message-ID: <30FA6031.39B8@usa1.com>
- References: <4d8d8f$b30@oznet07.ozemail.com.au>
- NNTP-Posting-Host: wmn1-175.usa1.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0b5 (Macintosh; I; PPC)
-
- Oliver Jones wrote:
- >
- > Email reply's please.
- >
- > Could someone please explain to me the significance of the "const" in
- > this member function declaration.
- >
- > int MyFunc(const char *s) const {
- > ...
- > };
- >
- > I became aware of these when my compiler complained I couldn't call a
- > non-const member function from a pointer to a const parameter class.
- > eg: I couldn't do this:
- >
- > int MyFunc2(const TMyClass *p) {
- > int i = p->MyFunc("hi");
- > }
- >
- > I needed to add the const to the declaration above. Care to explain
- > the significance and "side effects" of the const member as defined
- > above.
- >
- > Thanks.
-
- The meaning of the trailing const in the function declaration is a
- promise to the compiler that the member function MyFunc() will not
- modify the state of *this. In MyFunc2(), *p is a pointer to a const
- TMyClass object (NOT a const pointer to a TMyClass object).
- Therefore, in the scope of MyFunc2(), *p will be const, and you can
- only call those member functions that promise not to alter its
- state, i.e., the const member functions.
-